package net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import net.handler.AccepHandler;
import net.im.IMMessagePacket;

public class Client implements Runnable {

	private MulticastSocket msSocket;
	private DatagramPacket packet;
	private ByteArrayInputStream inBuffers;
	private ByteArrayOutputStream otBuffers;
	private ObjectInputStream Obin;
	private byte[] data = new byte[1024 * 4];

	private InetAddress ip;
	private int port = 38400;

	public Client() {
		try {
			this.msSocket = new MulticastSocket(port);
			ip = InetAddress.getByName("230.0.0.1");
			msSocket.joinGroup(ip);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 发送
	public void send(IMMessagePacket sendMessage) {
		try {
			otBuffers = new ByteArrayOutputStream();
			ObjectOutputStream obOut = new ObjectOutputStream(otBuffers);
			obOut.writeObject(sendMessage);
			obOut.close();
			DatagramPacket data=new DatagramPacket(otBuffers.toByteArray(), otBuffers.toByteArray().length,ip,port);
			msSocket.send(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				packet = new DatagramPacket(data, data.length);
				// 接收数据
				msSocket.receive(packet);
				inBuffers = new ByteArrayInputStream(packet.getData());
				ObjectInputStream obIn = new ObjectInputStream(inBuffers);
				IMMessagePacket obj = (IMMessagePacket) obIn.readObject();
				// 推送数据
				AccepHandler.getAccepHandler().setPushData(obj);
			} catch (IOException | ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
}
